package com.phaethon.centerofuser.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.phaethon.centerofuser.common.BaseResponse;
import com.phaethon.centerofuser.common.ErrorCode;
import com.phaethon.centerofuser.common.ResultUtils;
import com.phaethon.centerofuser.contant.UserConstant;
import com.phaethon.centerofuser.exception.BusinessException;
import com.phaethon.centerofuser.model.domain.domain.User;
import com.phaethon.centerofuser.model.request.UserLoginRequest;
import com.phaethon.centerofuser.model.request.UserRegisterRequest;
import com.phaethon.centerofuser.service.UserService;
import com.phaethon.centerofuser.service.impl.UserServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.phaethon.centerofuser.contant.UserConstant.ADMIN_ROLE;
import static com.phaethon.centerofuser.contant.UserConstant.USER_LOGIN_STATE;

/**
 * @author Phaethon
 *
 * 实现用户接口
 */

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserServiceImpl userServiceImpl;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if (userRegisterRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)){
            throw new BusinessException(ErrorCode.PARAM_NULL_ERROR,"缺少必填项");
        }

        long result = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        if (userLoginRequest == null){
            throw new BusinessException(ErrorCode.PARAM_NULL_ERROR,"无登录请求");
        }

        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)){
            throw new BusinessException(ErrorCode.PARAM_NULL_ERROR,"未输入账号密码");
        }

        User result =  userService.userLogin(userAccount, userPassword,request);
        return ResultUtils.success(result);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request){
        if (request == null) {
            return null;
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username , HttpServletRequest request){
        // 仅管理员可查询，验证权限
        // 访问静态方法应该用类UserService而不应该用对象
        if(!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH,"无权限访问管理页面");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)){
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> result = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(result);

    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null){
            throw new BusinessException(ErrorCode.NO_LOGIN,"未登录");
        }
        long userId = currentUser.getId();
        User user = userService.getById(userId);
        User safetyUser =  userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody Long id , HttpServletRequest request){
        // 仅管理员可删除，验证权限
        // 访问静态方法应该用类UserService而不应该用对象
        if(!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH,"无权使用该功能");
        }
        if (id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"id小于0");
        }
        Boolean result = userService.removeById(id);
        return ResultUtils.success(result);

    }

    /**
     * 是否为管理员
     */
    private boolean isAdmin(HttpServletRequest request){
        // 仅管理员可操作，验证权限
        // 访问静态方法应该用类UserService而不应该用对象
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }


}
